<template>
  <view class="o-page-content">
    <!-- <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar> -->
    <view v-if="orderStatus === 'WAIT_SELLER_SEND_GOODS' || 'WAIT_BUYER_CONFIRM_GOODS'" class="rma_listMob">
      <block v-for="(item, index) in list" :key="index">
        <view class="gInfo" v-if="item.refundStatus == 'CLOSED' || item.refundStatus == 'NO_REFUND' || item.shippedQty.length > 0">
          <view v-if="item.isGift != 1">
            <view class="label-1__icon" @click.stop="selectTap" :data-index="index" :data-orderItemId="item.orderItemId"
              :data-refundFee="item.price">
              <icon v-if="item.isSelect" size="15" class="icon_check" type="success_no_circle" color="#444444" />
            </view>
            <view class="u-float-left ram_listImg">
              <navigator :url=" '/pages/item/item?id=' + item.itemId + '&valueId=' + item.skuProperties[0].valueId "
                hover-class="none">
                <image :src="item.skuImageUrl" :style="{height:imageHeight+'rpx'}"></image>
              </navigator>
            </view>

            <view class="u-float-left ram_info">
              <strong>
                <navigator class="a-link" hover-class="none" :url=" '/pages/item/item?id=' + item.itemId + '&valueId=' + item.skuProperties[0].valueId ">{{item.itemName}}</navigator>
              </strong>
              <p>{{item.skuProperties[0].propertyName}}：{{item['skuProperties'][0].valueName}}</p>
              <p :style="{'opacity':item.skuProperties[1]?'1':'0'}">{{item.skuProperties[1].propertyName}}：{{item['skuProperties'][1].valueName}}</p>
              <view class="rmaNumber">
                数量：
                <picker
                  :value="refundIdx"
                  :range="item.shippedQty"
                  :data-id="item.orderItemId"
                  :data-index="index" mode="selector"
                  @change="bindRefundQtyChange">
                  <view class="picker">{{item.refundQty ? item.refundQty :1}}</view>
                  <span class="iconfont icon-jiantou32"></span>
                </picker>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>
    <view class="notice-box">
      <view class="o-contain">
        <view class="pop_Input">
          <view class="listMob">
            <label>退货原因：</label>
            <picker :value="reasonIdx" :range-key="'reason'" :range="reasonArr" mode="selector" @change="bindPickerChange">
              <view class="picker">{{reason?reason:'- 请选择原因 -'}}</view>
              <span class="iconfont icon-jiantou32"></span>
            </picker>
            <!-- 退货方式 -->
            <!-- <picker value="{{index}}" range="{{returnWayArr}}" mode="selector" bindchange="bindReturnWayChange" style="margin:20rpx 0">
                  <view class="picker">{{returnWayArr[returnWay] ? returnWayArr[returnWay] : '- 请选择退货方式 -'}}</view>
                  <span class="iconfont icon-jiantou32"></span>
                </picker> -->
            <!-- <view class="storeInfo" @click="showStoreInfo">查看门店信息</view> -->
          </view>
          <view class="listMob">
            <label>备注：</label>
            <textarea @input="remarkInput" :value="remark" class="textareaBox" name="textarea" />
            </view>
              <view class="bottom-section" :data-id="index">
                <button class="a-button is-primary" :class="buttonFlag?'':'btn_invalid'" @click="toRmaApply">提交</button>
                <!-- <button class="a-button is-primary" :class="reason !== '' && allowRefundPrice != 0  ?'':'btn_invalid'" @click="toRmaApply">提交</button> -->
              </view>
            </view>
            <!-- <view style="height:300rpx;">加高度</view> -->
          </view>
      </view>
			<!-- 弱提示 弹窗 -->
			<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
  import Vue from 'vue';
  import api from '@/api/api';
  // import NavBar from '../../components/common/navbar';
  import {
    SYSTEM_INFO,
    MERCHANT_INFO,
    CUSTOMER_INFO
  } from '@/utils/constant';
 export default {
   config: {
     navigationBarTitleText: '退货退款',
   },
   // components: {
   //   navBar: NavBar
   // },
   data() {
     return {
       // isShowCustomNavBar: true,
       // // 组件所需的参数
       // navbarData: {
       //   showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
       //   title: '' //导航栏 中间的标题
       // },
       isShowNotice:false,
       remark:'',   //备注
       orderNo: "",
       orderId: "",
       list:[],
       reasonArr: [],
       returnWayArr:['门店退货','线上退货'],
       returnWay:-1,
       reason: "",
       reasonIdx: 0,
       orderStatus: "",
       description:"",
       refundFee:[],
       refundFeePrice:0,
       orderItemId:[],
       orderRefundQtyArr:[],
       refundIdx:0,
       qtyItems:[],
       itemQtyArr:[],

       tmplIds:[], //微信订阅消息模板ID

       allowRefundPrice:0,
       imageHeight: 180,
        buttonFlag: false,
        nowPages:''
     }
   },

   onLoad(options) {
     this.orderNo=options.orderNo;
     this.imageHeight = 120 / uni.getStorageSync('imageScaling');
     this.getOrderInfo();
     let pages = getCurrentPages();
     var currPage = pages[pages.length - 1];
     this.nowPages = currPage.route;
   },
   onShow() {
    getApp().cl_tracker.track('mini_program_view', {
          path:  this.nowPages,
          pageName: '退货退款',
        }) 
   },
    watch: {
      orderItemId: function(val) {
        if (val.length > 0 && this.reason) {
          this.buttonFlag = true
        } else {
          this.buttonFlag = false
        }

      },
      reason: function(val) {
        if (this.orderItemId.length > 0 && val) {
          this.buttonFlag = true
        } else {
          this.buttonFlag = false
        }
      }
    },
    
   methods: {
		 /**
		  * 展示弱提示
		  * @param {Object} msg 文案
		  */
		 handleShowTextToast(msg){
		 	try{
		 		this.$refs.toastPopup.showToast(msg);
		 	}catch(e){}
		 },
		 /**
		  * 若提示按钮点击回调
		  * @param {Object} data.type 类型：confirm确定，cancel取消
		  * @param {Object} data.callBackData 呼气弹窗时传入的数据
		  */
		 onToastPopupClick(data){},
     refundQtyArr(qty){
       var itemQtys = [];
       for(var i=1;i<qty+1;i++){
         itemQtys.push(i);
       }
       return itemQtys;
     },


     // 获取商品详情
     getOrderInfo: async function() {
       let that = this;
       let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
       const json = await api.getOrderInfo({
         header: {'jwt': customerInfo.jwt},
       }, this.orderNo);

       if (json.code === 1000) {
         this.orderId = json.data.orderId;
         this.orderStatus = json.data.status;
         that.list=[];
         let allowRefund=[];
         allowRefund = json.data.items;
         //解析每个数组下面的items.skuProperties属性
         allowRefund.forEach(function (item, index, array) {
           allowRefund[index].skuProperties = JSON.parse(array[index].skuProperties);  //shippedQty

           var canRefundQty = array[index].shippedQty - array[index].refundQty;
           allowRefund[index].shippedQty = that.refundQtyArr(canRefundQty);
           allowRefund[index].refundQty = canRefundQty;

           allowRefund[index].refundFee =  (allowRefund[index].qty * allowRefund[index].price - allowRefund[index].discountFee) /  allowRefund[index].qty * allowRefund[index].refundQty

           if(allowRefund[index].refundQty > 0){
              that.list.push(allowRefund[index])
           }

         });

         this.addTag()

         this.getReasonList();
       } else {
         this.handleShowTextToast(json.msg);
       }
     },


     // 获取退款原因
     getReasonList: async function() {
       let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
       const json = await api.refundReason({
         header: {'jwt': customerInfo.jwt},
       });
       if (json.code === 1000) {
         this.reasonArr = json.data;
       }
     },

     addTag(){
       for(var i = 0; i < this.list.length; i++){
         this.list[i].isSelect = false;
       }
     },


     selectTap(e){
       let that = this;
       let index = -1;
       index = e.currentTarget.dataset.index;
       let rmaList = this.list;
       rmaList[index].isSelect = !rmaList[index].isSelect;
       this.list = rmaList;
       let refundItem = [];

        // 选中退货的商品
       for(let i in this.list){
         if(this.list[i].isSelect == true){
           if(refundItem.indexOf(this.list[i].orderItemId) == -1){
             refundItem.push(this.list[i])
           }
         }
       }

        let refundPrePrice = [];
        let refundItemId = [];
        that.itemQtyArr = [];
        that.qtyItems = [];
        var itemQty = [];

        for(let i in refundItem){
          if(refundPrePrice.indexOf(refundItem[i].orderItemId) == -1){
            refundPrePrice.push(refundItem[i].refundFee)
          }
          refundItemId.push({orderItemId:refundItem[i].orderItemId})
          that.itemQtyArr.push(refundItem[i].orderItemId);

          //默认设置退货数量为当前可退货数
          itemQty = {num :refundItem[i].refundQty,orderItemId:refundItemId[i].orderItemId,reason:that.reason};
          that.qtyItems.push(itemQty);

       }

       that.refundFee = refundPrePrice;
       that.orderItemId = refundItemId;
       let refundPrice = 0;
       if(this.refundFee !== null){
         for(let i in this.refundFee){
           refundPrice += this.refundFee[i];
         }
       }
       that.allowRefundPrice = refundPrice.toFixed(2)
       this.$forceUpdate()
     },




     // 退货方式
     bindReturnWayChange(e){
       this.returnWay = e.detail.value;
     },

     // 选择退货数量
     bindRefundQtyChange: function(e) {
       var that = this;
       that.refundIdx = 0;
       var list_index = e.currentTarget.dataset.index;  //索引
       var itemId = e.currentTarget.dataset.id;
       var idx = e.detail.value;
       that.refundIdx = idx;
       that.list[list_index].refundQty = that.list[list_index].shippedQty[idx];

       that.list[list_index].refundFee = (that.list[list_index].qty * that.list[list_index].price - that.list[list_index].discountFee) /  that.list[list_index].qty * that.list[list_index].refundQty ;

       // 退款金额
       let refundItem = [];
       for(let i in this.list){
         if(this.list[i].isSelect == true){
           if(refundItem.indexOf(this.list[i].orderItemId) == -1){
             refundItem.push(this.list[i])
           }
         }
       }

       let refundPrePrice = [];
       for(let i in refundItem){
         if(refundPrePrice.indexOf(refundItem[i].orderItemId) == -1){
           refundPrePrice.push(refundItem[i].refundFee)
         }
       }

       this.refundFee = refundPrePrice;
       let refundPrice = 0;
       if(this.refundFee !== null){
         for(let i in this.refundFee){
           refundPrice += this.refundFee[i];
         }
       }
       that.allowRefundPrice = refundPrice.toFixed(2)


       //组合退款item及数量数组，格式为
       /*                "items": [
        {
        "num": 0,
        "orderItemId": 0,
        "reason": "string"
        }
        ],*/
       var itemQty = {num :that.list[list_index].shippedQty[idx],orderItemId:itemId,reason:that.reason};
       if(that.list[list_index].isSelect == true){
         if(that.itemQtyArr.indexOf(itemId) >= 0){
           for(var i = 0;i<that.qtyItems.length;i++){
             if(that.qtyItems[i].orderItemId === itemId){
               that.qtyItems[i].num = that.list[list_index].shippedQty[idx];
               that.qtyItems[i].reason = that.reason;
             }
           }

         }else{
           that.itemQtyArr.push(itemId);
           that.qtyItems.push(itemQty);
         }
       }
     },

     // 选择退款原因
     bindPickerChange: function(e) {
       this.reasonIdx= e.detail.value;
       this.reason = this.reasonArr[this.reasonIdx].reason;
     },

     // 查看门店信息
     showStoreInfo(){
       var that = this;
       this.isShowNotice = true;
     },

     isShow(e){
       var that = this;
       this.isShowNotice = e;
     },

     // 备注
     remarkInput: function(e) {
       this.remark = e.detail.value;
     },

    // 获取模板ID 微信订阅消息
    getTmplIds: async function() {
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
      const tmplIds = await api.customize({
        method: "POST",
        query: {
          "cloudMerchantId": merchantInfo.cloudMerchantId,
          "cloudMerchantStoreId": merchantInfo.cloudMerchantStoreId,
          "cloudStoreConfigtypeId": 59,
          "cloudStoreConfigtypeName": "Mini_Subscribe_Message_Config",
        },
      });
      if (tmplIds.code == 200) {
        const configText = tmplIds.data.cloudStoreConfigText;
        let configTextParse = JSON.parse(configText);
        let orderMessage = [];
        // 填写退货信息通知
        if(configTextParse.returnMsg == 1) {
          orderMessage.push(configTextParse.returnTemplateId)
        }
        this.tmplIds = orderMessage;
      }
    },


     // 提交  0 -- 仅退款  1-- 退货退款
     toRmaApply: async function() {
       let that = this;
       let refundPrice = 0;

       that.getTmplIds();
       if(this.refundFee !== null){
         for(let i in this.refundFee){
           refundPrice += this.refundFee[i];
         }
       }
       if(this.reason !== "" && this.orderItemId.length != 0) {
         let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
         let goodStatus = this.orderStatus !== 'WAIT_BUYER_CONFIRM_GOODS' ?'BUYER_NOT_RECEIVED':'BUYER_RECEIVED';
         const json = await api.refundApply({
           method: 'POST',
           header: {'jwt': customerInfo.jwt},
           query: {
             "description":that.remark,
             "goodStatus": goodStatus,
             "hasGoodsReturn":1,
             "orderId": this.orderId,
             "items": this.qtyItems,
             "reason": this.reason,
             "refundFee": refundPrice,
           }
         });
         if (json.code === 1000) {
          let refundId = json.data.refundId;
          that.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗'})
          that.$commonSensors.modelAuthAsk('退货', that.tmplIds)
          uni.requestSubscribeMessage({
            tmplIds: that.tmplIds,
            complete(res) {
              setTimeout(() => {
               uni.redirectTo({
                 url: "/pages/return/applySuccess?orderNo=" + that.orderNo + "&refundId=" + refundId
               })
              }, 1000);
            },
          });


         }else{
           this.handleShowTextToast(json.msg)
         }
       }else{
         if(this.reason == ""){
           this.handleShowTextToast('退货原因不能为空')
         }
         if(this.orderItemId == ""){
           this.handleShowTextToast('请选择退货商品')
         }

       }
       return false;
     },

   }
 }


</script>
<style lang="less">
  @import "../../static/styles/style";
  page{background-color: #fff}
  button{padding:8rpx 0}
  picker{position: relative}
  .u-float-left{float:left}
  .gInfo{
    overflow: hidden;
    padding:0rpx 24rpx;
    background-color: #fff;
    position: relative;
  }
  .gInfo p{
    height:40rpx;
    line-height:40rpx;
    display:block;
    font-size:26rpx;
  }
  .gInfo strong{
    font-size:28rpx;
    margin:4rpx 0 10rpx;
    font-weight:700;
    display:block;
    height:40rpx;
    line-height:40rpx;
    max-width: 450rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
  .ram_listImg{
    display: block;
    margin:0 40rpx 0 60rpx
  }
  .ram_listImg image{
    width:120rpx;
    // height:180rpx;
    display: block
  }
  .bottom-section{
    margin:30px 0 20px;
  }
  .rma_listMob h4{
    font-size: 18px;
    text-align: center;
    margin: 20px 0;
    display: block
  }
  .pop_Input{
    width:100%;
    padding-bottom: 200rpx;
  }
  .listMob{margin-bottom:20rpx}
  .picker{
    height:26px;
    line-height:26px;
    border:1px solid #ccc;
    padding-left: 10rpx;
  }
  .icon-jiantou32{
    position: absolute;
    right: 4px;
    top: 3px;
    font-size: 20px;
  }
  .textareaBox{
    border:1px solid #ccc;
    width:97.8%;
    height:100rpx;
    padding:6rpx;
  }
  .ram_info{position: relative;}
  .rma_cancel{
    position: absolute;
    right:15rpx;
    top:24rpx;
    text-decoration: underline
  }
  .rma_listMob{padding:0 15rpx}
  label{
    font-size:28rpx;
  }
  .notice-box .o-contain{padding:60rpx 24rpx 0;}
  .notice-box .icon-cuowu1{
    font-size:68rpx;
    position: fixed;
    right:12rpx;
    top:0
  }
  .storeInfo{
    text-decoration: underline;
    display: inline-block;
    padding:10rpx 0 30rpx
  }
  .label-1__icon {
    position: relative;
    top:108rpx;
    width: 30rpx;
    height: 30rpx;
    background: #fcfff4;
    border: 1rpx solid #cccccc;
    padding: 5rpx;
  }

  .icon_check {
    position: absolute;
    width:30rpx;
    height:30rpx;
		left: -1rpx;
		top: -2rpx;
  }

  .rmaNumber{display:flex;margin-top: 2rpx;line-height: 46rpx;}
  .rmaNumber .picker{width:90rpx;}

</style>
